package com.mishow.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.Projection;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.services.core.PoiItem;
import com.mishow.R;
import com.mishow.activity.base.BaseActivity;
import com.mishow.adapter.MyKeyWordsLocationAdapter;
import com.mishow.log.MyLog;
import com.mishow.map.search.CustomMapSearch;
import com.mishow.refresh.PullPushRefreshLayout;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.Constants;
import com.mishow.utils.ToastUtil;
import com.mishow.widget.MyListView;

/**
 * 
 * 作者：wei.miao <br/>
 * 描述：发布通告地址搜索
 */
public class AnnunciateReleaseLocationActivity extends BaseActivity {

	private Button btn_back;
	
	private TextView btn_location_search;

	private PullPushRefreshLayout refreshLayout_mishow;
	private MyListView listview_data;

	private EditText edit_keyword;
	
	private MapView map_view;

	/**
	 * 定义AMap 地图对象的操作方法与接口
	 **/
	private AMap aMap;
	/**
	 * 设置用户界面的一个AMap。调用AMap 的getUiSettings() 方法可以获得类的实例
	 **/
	private UiSettings mUiSettings;
	/**
	 * 定义了一个marker 的选项
	 **/
	private MarkerOptions markerOption;
	/**
	 * Marker 是在地图上的一个点绘制图标
	 **/
	private Marker marker2;// 有跳动效果的marker对象
	private LatLng latlng;
	/**
	 * 关键字
	 **/
	private String mKeyword;
	/**
     * 纬度
     **/
    private double latitude;
    /**
     * 经度
     **/
    private double longitude;
    
    private CustomMapSearch mCustomMapSearch;

	private MyKeyWordsLocationAdapter myClinicSearchKeywordAdapter;

	/**
	 * 表示查第几页 从第0页开始
	 **/
	private int mPageNum = 0;
	/**
	 * 总页数
	 **/
	private int mPageCount;
	/**
	 * poi数据列表
	 **/
	private ArrayList<PoiItem> mPoiItemList;
	
	private boolean isInit;
	
	private String cityCode;

	public static void intoActivity(Context context,String cityCode) {

		Intent intent = new Intent(context,AnnunciateReleaseLocationActivity.class);
		intent.putExtra(Constants.ANNUNCIATE_LOCATION_EXTRA_CODE, cityCode);
		((Activity)context).startActivityForResult(intent, Constants.ANNUNCIATE_LOCATION_REQUEST_CODE);

	}

	@Override
	protected void initData() {
		latitude = 39.90403;
		longitude = 116.407525;
		latlng = new LatLng(latitude, longitude);
		if (getIntent() != null) {
			
			cityCode = getIntent().getStringExtra(Constants.ANNUNCIATE_LOCATION_EXTRA_CODE);
		}else{
			cityCode = "110100";
		}
		
		isInit = true;
	}

	@Override
	protected void initView(Bundle savedInstanceState) {

		setContentView(R.layout.activity_annunciatelocation);

		btn_back = (Button) findViewById(R.id.btn_back);
		
		btn_location_search = (TextView)findViewById(R.id.btn_location_search);
		
		map_view = (MapView) findViewById(R.id.map_view);
		refreshLayout_mishow = (PullPushRefreshLayout) findViewById(R.id.refreshLayout_mishow);
		listview_data = (MyListView) findViewById(R.id.listview_data);
		edit_keyword = (EditText) findViewById(R.id.edit_keyword);

		// 在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
		map_view.onCreate(savedInstanceState);// 此方法必须重写
		initMapView();
	}

	@Override
	protected void setAttribute() {

		btn_back.setOnClickListener(onClickListener);
		btn_location_search.setOnClickListener(onClickListener);
		
		mCustomMapSearch = new CustomMapSearch(mContext,mOnPoiSearchResultListener);
		mPoiItemList = new ArrayList<PoiItem>();

		myClinicSearchKeywordAdapter = new MyKeyWordsLocationAdapter(mContext,mPoiItemList);

		listview_data.setOnItemClickListener(onItemClickListener);
		listview_data.setAdapter(myClinicSearchKeywordAdapter);

		// 禁用下拉刷新
		refreshLayout_mishow.setEnabled(false);
		refreshLayout_mishow.setListView(listview_data);
		refreshLayout_mishow.setOnLoadListener(onLoadListener);
		
		doSearchQuery();

	}

	private void initMapView() {

		if (aMap == null) {

			aMap = map_view.getMap();
			mUiSettings = aMap.getUiSettings();
			setUpMap();
		}
		// 设置地图是否可以手势缩放大小
		mUiSettings.setZoomGesturesEnabled(true);
		// 设置地图默认的缩放按钮是否显示
		mUiSettings.setZoomControlsEnabled(false);
		// 设置地图是否可以手势滑动
		mUiSettings.setScrollGesturesEnabled(true);

		// 设置地图默认的定位按钮是否显示
		// mUiSettings.setMyLocationButtonEnabled(false);
		// 是否可触发定位并显示定位层
		// aMap.setMyLocationEnabled(false);

	}

	private void setUpMap() {
		// aMap.setOnMarkerDragListener(this);// 设置marker可拖拽事件监听器
		aMap.setOnMapLoadedListener(onMapLoadedListener);// 设置amap加载成功事件监听器
		// aMap.setOnMarkerClickListener(onMarkerClickListener);//
		// 设置点击marker事件监听器
		// aMap.setOnInfoWindowClickListener(onInfoWindowClickListener);//
		// 设置点击infoWindow事件监听器
		aMap.setInfoWindowAdapter(infoWindowAdapter);// 设置自定义InfoWindow样式
		addMarkersToMap();// 往地图上添加marker
	}

	/**
	 * 在地图上添加marker
	 */
	private void addMarkersToMap() {
		// 系统默认marker背景图片
		// BitmapDescriptorFactory.HUE_AZURE
		// 动画效果
		// ArrayList<BitmapDescriptor> giflist = new
		// ArrayList<BitmapDescriptor>();
		// giflist.add(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
		// giflist.add(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
		// giflist.add(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
		markerOption = new MarkerOptions();
		// 定义marker 图标的锚点
		markerOption.anchor(0.5f, 0.5f);
		// 设置当前MarkerOptions 对象的经纬度
		markerOption.position(latlng);
		// 设置 Marker 的标题
		// markerOption.title(titleName == null ?"北京市":titleName);
		// 多图片刷新模拟gif动画 icons 设置会使用 icon方法覆盖
		// markerOption.icons(giflist);

		markerOption.icon(BitmapDescriptorFactory
				.fromResource(R.drawable.icon_clinic_loaction_pin));
		// 设置标记是否可拖动
		markerOption.draggable(true);
		// 设置多少帧刷新一次图片资源
		markerOption.period(10);

		marker2 = aMap.addMarker(markerOption);
		marker2.showInfoWindow();

	}

	/**
	 * 对marker标注点点击响应事件
	 */
	private AMap.OnMarkerClickListener onMarkerClickListener = new AMap.OnMarkerClickListener() {
		@Override
		public boolean onMarkerClick(Marker marker) {
			if (marker.equals(marker2)) {
				if (aMap != null) {
					jumpPoint(marker);
				}
			}
			return false;
		}
	};
	/**
	 * 监听amap地图加载成功事件回调
	 */
	private AMap.OnMapLoadedListener onMapLoadedListener = new AMap.OnMapLoadedListener() {

		@Override
		public void onMapLoaded() {

			// 设置所有maker显示在当前可视区域地图中
			// latLng - 可视区域框移动目标点屏幕中心位置的经纬度
			// zoom - 可视区域的缩放级别，高德地图支持3-20 级的缩放级别
			aMap.moveCamera((CameraUpdateFactory.newLatLngZoom(latlng, 16)));

		}
	};

	/**
	 * 监听自定义infowindow窗口的infoWindow事件监听器
	 */
	private AMap.OnInfoWindowClickListener onInfoWindowClickListener = new AMap.OnInfoWindowClickListener() {

		@Override
		public void onInfoWindowClick(Marker marker) {

		}
	};

	/**
	 * 监听自定义infowindow窗口的infowindow事件回调
	 */
	private AMap.InfoWindowAdapter infoWindowAdapter = new AMap.InfoWindowAdapter() {

		@Override
		public View getInfoWindow(Marker marker) {

			View infoWindow = getLayoutInflater().inflate(
					R.layout.custom_info_window, null);

			render(marker, infoWindow);
			return infoWindow;
		}

		@Override
		public View getInfoContents(Marker marker) {
			return null;
		}
	};

	/**
	 * 自定义infowinfow窗口
	 */
	public void render(Marker marker, View view) {
		String title = marker.getTitle();
		TextView titleUi = ((TextView) view.findViewById(R.id.txt_info_title));
		if (title != null) {
			// SpannableString titleText = new SpannableString(title);
			// titleText.setSpan(new
			// ForegroundColorSpan(getResources().getColor(R.color.color_clinic_location_text)),
			// 0, titleText.length(), 0);
			titleUi.setText(title);
		} else {
			titleUi.setText("");
		}
	}

	/**
	 * marker点击时跳动一下
	 */
	public void jumpPoint(final Marker marker) {
		final Handler handler = new Handler();
		final long start = SystemClock.uptimeMillis();
		Projection proj = aMap.getProjection();
		Point startPoint = proj.toScreenLocation(latlng);
		startPoint.offset(0, -100);
		final LatLng startLatLng = proj.fromScreenLocation(startPoint);
		final long duration = 1500;

		final Interpolator interpolator = new BounceInterpolator();
		handler.post(new Runnable() {
			@Override
			public void run() {
				long elapsed = SystemClock.uptimeMillis() - start;
				float t = interpolator.getInterpolation((float) elapsed
						/ duration);

				double lng = t * latlng.longitude + (1 - t)
						* startLatLng.longitude;
				double lat = t * latlng.latitude + (1 - t)
						* startLatLng.latitude;

				marker.setPosition(new LatLng(lng, lat));
				aMap.invalidate();// 刷新地图
				if (t < 1.0) {
					handler.postDelayed(this, 16);
				}
			}
		});

	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_back:
				finish();
				break;
			case R.id.btn_location_search:
				if (AndroidUtil.isNetworkAvailable(mContext)) {
					mKeyword = checkEditText(edit_keyword);
					if ("".equals(mKeyword)) {
						ToastUtil.show(mContext, "请输入搜索关键字");
					} else {
						isInit = false;
						doSearchQuery();
					}
                    
                }else{
                    ToastUtil.show(mContext,"网络连接异常,请检查网络");
                }
				break;

			default:
				break;
			}

		}
	};

	@Override
	public void onResume() {
		super.onResume();
		// 在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
		map_view.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
		// 在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
		map_view.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		map_view.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		// 在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState
		// (outState)，实现地图生命周期管理
		map_view.onSaveInstanceState(outState);
	}

	// 处理搜索功能-----------------------------------------------
	/**
	 * 搜索回调
	 */
	private CustomMapSearch.OnPoiSearchResultListener mOnPoiSearchResultListener = new CustomMapSearch.OnPoiSearchResultListener() {
		@Override
		public void onSearchSuccess(List<PoiItem> poiItems, int pageCount) {
			MyLog.d("MV", "搜索成功=====返回该结果的总页数=" + pageCount);
			mPageCount = pageCount;
			mPoiItemList.addAll(poiItems);
			myClinicSearchKeywordAdapter.notifyDataSetChanged();
			loadCompleted();
			dismissProgress();
		}

		@Override
		public void onSearchFail(int reCode) {
			if (reCode != 1000) {
				ToastUtil.show(mContext, "没有找到该位置信息");
			}
			loadCompleted();
			dismissProgress();
		}
	};

	/**
	 * 加载更多接口
	 */
	private PullPushRefreshLayout.OnLoadListener onLoadListener = new PullPushRefreshLayout.OnLoadListener() {
		@Override
		public void onLoad() {

			MyLog.d("MV", "mPageNum=" + mPageNum);
			if (mPageNum < mPageCount) {
				mPageNum++;
				if (isInit) {
					mCustomMapSearch.doSearchKeyword("", "科教文化服务|生活服务", cityCode, mPageNum);
				}else{
					mCustomMapSearch.doSearchKeyword(mKeyword, "",cityCode, mPageNum);
				}
			} else {

				loadCompleted();
			}

		}
	};

	private void doSearchQuery() {
		mPageNum = 0;
		if (isInit) {
			mCustomMapSearch.doSearchKeyword("", "科教文化服务|生活服务", cityCode, mPageNum);
			return;
		}
		showProgress();
		if (mPoiItemList != null) {
			mPoiItemList.clear();
			myClinicSearchKeywordAdapter.notifyDataSetChanged();
		}
		mCustomMapSearch.doSearchKeyword(mKeyword, "",cityCode, mPageNum);
	}

	/**
	 * 加载完成
	 */
	private void loadCompleted() {

		refreshLayout_mishow.setRefreshing(false);
		refreshLayout_mishow.setLoading(false);
		// 获取到全部数据后，则隐藏加载更多
		if (mPageNum < mPageCount) {
			refreshLayout_mishow.setCanLoadMore(true);
		} else {
			refreshLayout_mishow.setCanLoadMore(false);
		}
	}

	private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {

			PoiItem poiItem = mPoiItemList.get(position);
			Intent intent = new Intent();
			intent.putExtra(Constants.ANNUNCIATE_LOCATION_EXTRA_NAME, poiItem);
			setResult(RESULT_OK, intent);
			finish();
		}
	};

	/**
	 * 判断edittext是否null
	 */
	public String checkEditText(EditText editText) {
		if (editText != null && editText.getText() != null
				&& !(editText.getText().toString().trim().equals(""))) {
			return editText.getText().toString().trim();
		} else {
			return "";
		}
	}
}
